<template>
  <!-- 测试主容器 -->
  <div class="test-container">
    <!-- 加载中动画 -->
    <div v-if="loading || !isTestDataValid" class="loading-container">
      <div class="loading-spinner"></div>
      <p>Loading...</p>
    </div>

    <template v-else>
      <!-- 阶段结果页面，完成一个阶段后显示，不跳转新页面 -->
      <div v-if="showStageResult" class="stage-result" :key="`stage-result-${completedStageId}`">
        <div class="result-content">
          <div class="result-image">
            <img :src="stageResultData.image | imgPath" alt="Stage result" />
          </div>
          <h2 class="result-title">{{ stageResultData.title || 'New Stage!' }}</h2>
          <p class="result-stats" v-html="stageResultData.remark"></p>
          <div class="stage-buttons">
            <button class="continue-btn" @click="continueToNextStage">Continue</button>
            <button class="back-btn" @click="backToLastQuestion">Previous question</button>
          </div>
        </div>
      </div>

      <!-- 阶段1：图片选择题组件 -->
      <question-type-one
        v-else-if="currentStage === 1 && currentQuestionData"
        :key="`question-type-one-${currentQuestion}`"
        :question="currentQuestionData"
        :questionNumber="currentQuestionInStage + 1"
        :totalQuestions="currentStageQuestions.length"
        :stageNumber="currentStage"
        :progress="progressPercentage"
        @select-option="handleSelectOption"
        @next-question="nextQuestion"
        @prev-question="prevQuestion"
      />

      <!-- 阶段2-4：普通选择题组件 -->
      <question-type-two
        v-else-if="currentStage >= 2 && currentStage <= 4 && currentQuestionData"
        :key="`question-type-two-${currentQuestion}`"
        :question="currentQuestionData"
        :questionNumber="currentQuestionInStage + 1"
        :totalQuestions="currentStageQuestions.length"
        :stageNumber="currentStage"
        :progress="progressPercentage"
        @select-option="handleSelectOption"
        @next-question="nextQuestion"
        @prev-question="prevQuestion"
      />

      <!-- 阶段5：二选一题型组件（Would you rather） -->
      <question-type-three
        v-else-if="currentQuestionData"
        :key="`question-type-three-${currentQuestion}`"
        :question="currentQuestionData"
        :questionNumber="currentQuestionInStage + 1"
        :totalQuestions="currentStageQuestions.length"
        :stageNumber="currentStage"
        :progress="progressPercentage"
        @select-option="handleSelectOption"
        @next-question="nextQuestion"
        @prev-question="prevQuestion"
      />

      <!-- 如果无法加载问题数据显示错误提示 -->
      <div v-else class="loading-container">
        <p>无法加载问题数据，请刷新页面或清除缓存重试</p>
      </div>
    </template>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
import QuestionTypeOne from '../components/QuestionTypeOne.vue'
import QuestionTypeTwo from '../components/QuestionTypeTwo.vue'
import QuestionTypeThree from '../components/QuestionTypeThree.vue'
import api from '@/utils/api'

export default {
  name: 'Test',
  components: {
    QuestionTypeOne,
    QuestionTypeTwo,
    QuestionTypeThree,
  },
  data() {
    let qurey = this.$route.query
    return {
      uid: qurey.uid || localStorage.getItem('uid'),
      loading: false, // 是否处于加载状态
      showStageResult: false, // 是否显示阶段结果页
      completedStageId: null, // 当前完成的阶段ID
      stageResultData: {}, // 阶段结果数据
      answerQueue: [], // 答案上报队列
      isProcessingQueue: false, // 是否正在处理队列
      maxRetries: 3, // 最大重试次数
    }
  },
  computed: {
    // 映射全局状态
    ...mapState({
      currentStage: (state) => state.currentStage, // 当前阶段编号
      currentQuestion: (state) => state.currentQuestion, // 当前题目编号
      stageData: (state) => state.stageData, // 各阶段数据
    }),
    ...mapGetters(['currentStageData', 'currentQuestionData', 'testProgress', 'currentStageQuestions', 'isLastQuestionInStage', 'isLastQuestion']),
    // 检查测试数据是否有效
    isTestDataValid() {
      // 检查当前阶段的数据是否已加载
      return this.stageData && this.stageData[this.currentStage] && this.stageData[this.currentStage].list && this.stageData[this.currentStage].list.length > 0
    },
    // 当前阶段内的题目索引（从0开始）
    currentQuestionInStage() {
      return this.currentQuestion - 1
    },
    // 当前题目在本阶段的进度百分比
    progressPercentage() {
      if (!this.currentStageQuestions || !this.currentStageQuestions.length) return 0
      return Math.round(((this.currentQuestionInStage + 1) / this.currentStageQuestions.length) * 100)
    },
  },
  methods: {
    // 映射actions和mutations
    ...mapActions(['fetchStageData']),
    ...mapMutations(['setCurrentQuestion', 'setCurrentStage', 'addAnswer', 'resetTest']),
    // 处理用户选择的选项
    handleSelectOption(optionId, qId) {
      // 查找是否已存在该题的答案
      const existingAnswerIndex = this.$store.state.answers.findIndex((answer) => answer.stageId === this.currentStage && answer.questionId === this.currentQuestionInStage)

      // 如果已存在答案，先从数组中移除
      if (existingAnswerIndex !== -1) {
        this.$store.state.answers.splice(existingAnswerIndex, 1)
      }
      ta.track('test_q_submit', { answer_no: qId })
      // 记录新答案
      this.addAnswer({
        stageId: this.currentStage,
        questionId: this.currentQuestionInStage, // 当前题目编号索引
        selectedOption: optionId, // 用户选择的题目答案id,每个答案有一个id
        qId: qId, // 当前题目ID
      })

      // 注意：这里不立即跳转，而是让组件中的setTimeout延迟后触发nextQuestion
      // 组件内部有setTimeout(800ms)会自动调用nextQuestion方法
      // console.log('用户选择了选项:', optionId, '等待800ms后自动跳转...')
    },

    // 获取阶段过渡结果
    async fetchStageResult() {
      try {
        // 根据当前完成的阶段ID构建请求参数
        const params = {
          reportId: 1, // 固定值为1
          partId: this.completedStageId, // 当前完成的阶段ID (1,2,3,4)
        }
        // 调用API获取阶段过渡结果
        const response = await api.getTransitionalResult(params)
        // 检查响应
        if (response.code === 200 && response.data) {
          this.stageResultData = response.data
          // console.log('result:', this.stageResultData)
        }
      } catch (error) {
        // console.log('未获取到阶段过渡结果')
      }
    },
    // 跳转到下一题或显示阶段结果
    async nextQuestion() {
      // 获取当前题目ID和用户选择
      const currentAnswer = this.$store.state.answers.find((answer) => answer.stageId === this.currentStage && answer.questionId === this.currentQuestionInStage)
      if (currentAnswer) {
        // 将答案加入队列而不是直接上报
        this.addToAnswerQueue({
          questionId: currentAnswer.qId,
          answerId: currentAnswer.selectedOption,
          reportId: 1,
        })
      }

      // 检查是否是整个测试的最后一题
      if (this.isLastQuestion) {
        // 导航到最终结果页面前确保所有答案都已上报
        this.toResult()
        this.flushAnswerQueue()
        return
      }

      // 检查是否是当前阶段的最后一题
      if (this.isLastQuestionInStage) {
        // 如果不是最后一个阶段
        if (this.currentStage < 5) {
          // 显示当前阶段结果页面
          this.completedStageId = this.currentStage
          // 获取阶段过渡结果
          await this.fetchStageResult()
          this.showStageResult = true
          ta.track('test_trans_show', { stage: this.currentStage, report_id: this.uid })
        } else {
          // 最后一个阶段的最后一题，导航到结果页
          // 确保所有答案都已上报
          this.toResult()
          this.flushAnswerQueue()
        }
      } else {
        // 否则转到下一个问题
        this.setCurrentQuestion(this.currentQuestion + 1)
        // console.log('转到下一个问题')
      }

      // 在后台处理队列
      if (!this.isProcessingQueue) {
        this.processAnswerQueue()
        // console.log('后台处理队列')
      }
    },
    toResult() {
      this.$router.replace({
        path: '/result',
        query: {
          uid: this.uid,
        },
      })
    },

    // 跳转到上一题
    async prevQuestion() {
      try {
        // 如果是当前阶段的第一题
        if (this.currentQuestionInStage === 0) {
          // 如果不是第一阶段，则跳转到上一阶段的最后一题
          if (this.currentStage > 1) {
            const prevStage = this.currentStage - 1

            // 确保上一阶段的数据已加载
            if (!this.stageData[prevStage]) {
              // console.log('加载上一阶段数据')
              await this.fetchStageData(prevStage)
            }

            // 获取上一阶段的题目列表
            const prevStageData = this.stageData[prevStage]
            if (!prevStageData || !prevStageData.list || !prevStageData.list.length) {
              // console.error('无法获取上一阶段数据')
              return
            }

            // 获取上一阶段的最后一题编号
            const lastQuestionNumber = prevStageData.list.length

            // 先设置题目编号，再设置阶段
            this.setCurrentQuestion(lastQuestionNumber)
            this.setCurrentStage(prevStage)
          }
        } else {
          // 正常跳转到上一题
          this.setCurrentQuestion(this.currentQuestion - 1)
        }
      } catch (error) {
        // console.error('跳转到上一题时出错:', error)
      }
    },
    // 阶段结果页点击"继续"进入下一阶段
    async continueToNextStage() {
      // 获取API返回的下一阶段ID，如果不存在则使用当前阶段+1
      const nextStage = this.stageResultData.nextPartId || this.currentStage + 1

      // 确保下一阶段的数据已加载
      if (!this.stageData[nextStage]) {
        this.loading = true
        // console.log('加载下一阶段数据')
        await this.fetchStageData(nextStage)
        this.loading = false
      }

      this.setCurrentStage(nextStage)
      this.setCurrentQuestion(1)
      this.showStageResult = false
      window.scrollTo(0, 0)
      ta.track('test_trans_next', { stage: this.currentStage, report_id: this.uid })
    },
    // 返回到上一阶段的最后一题
    backToLastQuestion() {
      // 隐藏阶段结果页面
      this.showStageResult = false

      // 确保当前阶段数据存在
      if (!this.currentStageQuestions || !this.currentStageQuestions.length) {
        // console.error('当前阶段数据不完整')
        return
      }

      // 设置到当前阶段的最后一题
      this.setCurrentQuestion(this.currentStageQuestions.length)
    },
    // 添加新方法：将答案添加到队列
    addToAnswerQueue(answer) {
      this.answerQueue.push({
        ...answer,
        retries: 0,
        timestamp: Date.now(),
      })
    },

    // 添加新方法：处理答案队列
    async processAnswerQueue() {
      if (this.answerQueue.length === 0 || this.isProcessingQueue) {
        return
      }

      this.isProcessingQueue = true

      while (this.answerQueue.length > 0) {
        const answer = this.answerQueue[0]

        try {
          await api.reportAnswerApi({
            questionId: answer.questionId,
            answerId: answer.answerId,
            reportId: answer.reportId,
          })

          // 上报成功，从队列中移除
          this.answerQueue.shift()
        } catch (error) {
          // 上报失败，尝试重试
          if (answer.retries < this.maxRetries) {
            // 增加重试次数
            answer.retries++
            // 将失败的请求移到队列末尾，稍后重试
            this.answerQueue.shift()
            this.answerQueue.push(answer)
          } else {
            // 超过最大重试次数，放弃此答案
            this.answerQueue.shift()
            // console.error('上报答案失败，已达最大重试次数:', answer)
          }
        }
        // 函数有等待时用await await后一定要加Promise  等待的标志：resolve
        // 增加短暂延迟，避免请求过于频繁
        await new Promise((resolve) => setTimeout(resolve, 200))
      }

      this.isProcessingQueue = false
    },

    // 添加新方法：强制处理所有队列中的答案
    async flushAnswerQueue() {
      // 如果队列为空，直接返回
      if (this.answerQueue.length === 0) {
        return
      }

      // 如果有答案未上报，使用更激进的策略尝试上报
      const promises = this.answerQueue.map((answer) =>
        api
          .reportAnswerApi({
            questionId: answer.questionId,
            answerId: answer.answerId,
            reportId: answer.reportId,
          })
          .catch((error) => {
            // 忽略错误，确保不会阻止用户流程
            // console.error('最终上报尝试失败:', error)
          })
      )

      // 等待所有请求完成或超时
      await Promise.all(promises)

      // 清空队列
      this.answerQueue = []
    },
  },
  async created() {
    try {
      // 页面刷新时先等待数据加载
      this.loading = true

      // 如果已有stageData数据，直接使用
      if (this.stageData && this.stageData[this.currentStage]) {
        // console.log('使用已加载的阶段数据')
        this.loading = false
        return
      }

      // 获取当前阶段数据
      // console.log('加载当前阶段数据:', this.currentStage)
      await this.fetchStageData(this.currentStage)

      // 等待Vue更新计算属性
      await this.$nextTick()
      this.loading = false
    } catch (error) {
      // console.error('加载测试数据失败:', error)
      this.loading = false
    }
  },
  mounted() {
    ta.track('test_q_show', { stage: this.currentStage, q_no: this.currentQuestion, report_id: this.uid })
  },
  beforeDestroy() {
    // 确保在离开页面前尝试上报所有答案
    this.flushAnswerQueue()
  },
}
</script>

<style scoped>
.test-container {
  background: #e2e4f5;
  min-height: 100vh;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-size: 16px;
  font-family: NotoSans;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #7b5cff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 阶段结果样式 */
.stage-result {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 0;
}

.result-content {
  background-color: #e2e4f5;
  max-width: 500px;
  width: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  min-height: 100vh;
  position: relative;
}

.result-image {
  margin-top: 80px;
  width: 200px;
  height: 200px;
  /* margin-bottom: 24px; */
}

.result-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.result-title {
  font-size: 22px;
  font-weight: 700;
  color: #553b97;
  margin-bottom: 10px;
  font-family: NotoSans-ExtraBold;
}

.result-description {
  font-size: 14px;
  font-weight: normal;
  line-height: normal;
  text-align: center;
  letter-spacing: normal;
  color: #4733b2;
}

.result-stats {
  font-size: 14px;
  color: #553b97;
  /* margin-bottom: 30px; */
  white-space: pre-line;
  text-align: center;
}

.stage-buttons {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  max-width: 100%;
  margin-top: 50px;
  /* position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%); */
}

.back-btn {
  width: 100%;
  border-radius: 112px;
  box-sizing: border-box;
  border: 1px solid #775ae0;
  padding: 14px 20px;
  border-radius: 24px;
  font-size: 18px;
  color: #775ae0;
  font-family: NotoSans-SemiBold;
  background-color: #e2e4f5;
}

/* .back-btn:hover {
  background: #7a6ba6;
} */

.continue-btn {
  background: #775ae0;
  color: white;
  border: none;
  border-radius: 24px;
  padding: 14px 20px;
  font-size: 18px;
  font-weight: 600;
  width: 100%;
  /* cursor: pointer; */
  transition: background 0.2s;
  font-family: NotoSans-SemiBold;
}

.continue-btn:hover {
  background: #7a6ba6;
}
</style>
